package com.bot.rf;

import com.bot.rf.config.UserConfig;
import com.bot.rf.entity.BarcodeUtil;
import com.bot.rf.entity.BookInfo;
import com.bot.rf.entity.BookLocation;
import com.bot.rf.sql.DatabaseUtil;
import com.bot.rf.sql.util.LocalSqlUtil;
import com.bot.rf.util.FileUtil;
import com.bot.rf.util.WebServiceUtil;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.*;

import static com.bot.rf.util.FileUtil.readFileBackSet;
import static com.bot.rf.util.MyLogger.LOGGER;

/**
 * @program: report-form-demo
 * @description: res文件处理类
 * @author: zyy
 * @create: 2021-02-25 11:02
 **/
public class Res2Database {

    /**
     * res文件异常
     */
    private static boolean RES_ILLEGAL = false;

    /**
     * 报表日期
     */
    private static String REPORT_DATE;

    /**
     * 报表保存路径
     */
    private String reportPath;

    /**
      res文件路径
     */
    private String resPath;

    /**
     * 图书集合
     */
    private Map<String, BookInfo> bookMap;

    /**
     * 异常图书个数
     */
    private int abnormalBookNums = 0;

    /**
     * 构造函数
     *
     * @param filePath res文件路径（rfid）
     */
    Res2Database(String filePath) {
        // 初始化参数
        bookMap = new TreeMap<>();
        resPath = filePath;
        String resName = new File(resPath).getName();
        if (resName.length() < 15) {
            LOGGER.warn("res文件命名不规范：" + resName + "，长度小于15");
            return;
        } else {
            REPORT_DATE = resName.substring(3, 13);
        }
        String fileName = resPath.replaceAll("^.+\\\\", "").replace(".res", "");
        String fileDir = FileSystemView.getFileSystemView().getHomeDirectory().getPath() + "\\报表";
        File file = new File(fileDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        reportPath = fileDir + File.separator + fileName + ".xlsx";
        LOGGER.info("从XML中初始化设置成功！");
        errorDatabase(resPath);
        // 处理res文件
        handleRes(resPath);
        if (RES_ILLEGAL){
            return;
        }
        LOGGER.info("排序后，res有效数据：" + bookMap.size() + "条");
    }

    /**
     * 异常数据处理
     * @param filePath
     */
    public void errorDatabase(String filePath){
        LOGGER.info("处理异常数据...");
        if (UserConfig.HTTP_DATABASE){
            Set<String> resFileContents = readFileBackSet(filePath);
            if (resFileContents.size() < 2) {
                RES_ILLEGAL = true;
                LOGGER.info("res异常");
                return;
            }
            List<BookInfo> needUpdateTag = new ArrayList<>();
            for (String data : resFileContents) {
                data = data.replaceAll("[^\\w|\\d| ]", "");
                String[] resIn = data.split(" ");
                String tagId = resIn[0];
                BookLocation bookLocation = new BookLocation(
                        resIn[1], resIn[2],
                        resIn[3], resIn[4],
                        resIn[5], resIn[6],
                        resIn[7], resIn[9]);
                // 4B  8A 过滤
                if (bookLocation.getRowNo() == 8 || bookLocation.getRowNo() == 15){
                    continue;
                }
                // epc 模式
                String barcode = BarcodeUtil.epcToBarcode(tagId);
                if (barcode.length() < 6){
                    LOGGER.info("过滤 " + tagId + "   " + barcode);
                    continue;
                }
                BookInfo bookInfo = LocalSqlUtil.queryByBarcode(barcode);
                if (bookInfo == null){
                    bookInfo = new BookInfo();
                    bookInfo.setBarcode(barcode);
                    bookInfo.setTagId(tagId);
                    needUpdateTag.add(bookInfo);
                }
            }
            updateErrorInfos(needUpdateTag);
        }
    }

    /**
     * 处理res文件
     */
    public void handleRes(String filePath) {
        // 读取res文件
        Set<String> resFileContents = readFileBackSet(filePath);
        if (resFileContents.size() < 2) {
            RES_ILLEGAL = true;
            LOGGER.info("res异常");
            return;
        }
        List<BookInfo> updateData = new ArrayList<>();
        for (String data : resFileContents) {
            data = data.replaceAll("[^\\w|\\d| ]", "");
            String[] resIn = data.split(" ");
            String tagId = resIn[0];
            BookLocation bookLocation = new BookLocation(
                    resIn[1], resIn[2],
                    resIn[3], resIn[4],
                    resIn[5], resIn[6],
                    resIn[7], resIn[9]);
            // 4B  8A 过滤
            if (bookLocation.getRowNo() == 8 || bookLocation.getRowNo() == 15){
                continue;
            }
            // epc 模式
            String barcode = BarcodeUtil.epcToBarcode(tagId);
            BookInfo bookInfo = LocalSqlUtil.queryByBarcode(barcode);
            // 异常图书
            if (bookInfo == null) {
                bookInfo = new BookInfo(tagId, barcode, "", "");
                bookInfo.setAbnormal(true);
            }else{
                bookInfo.setLocation(bookLocation);
                updateData.add(bookInfo);
            }
            bookInfo.setTagId(tagId);
            bookInfo.setLocation(bookLocation);
            bookMap.put(tagId, bookInfo);
        }
        updateLocalDatabase(updateData);
    }

    public void updateErrorInfos(List<BookInfo> bookInfos){
        LOGGER.info("查询webservice接口... " + bookInfos.size() + "条");
        List<BookInfo> list = WebServiceUtil.updateByBarcode(bookInfos);
        LOGGER.info("查询结束，开始更新... " + bookInfos.size() + "条");
        LocalSqlUtil.batchUpdateBookInfo(list);
        LOGGER.info("更新结束... ");
    }

    /**
     * 更新本地数据库
     */
    public void updateLocalDatabase(List<BookInfo> socketData){
        if (UserConfig.UPDATE_DATABASE){
            LOGGER.info("更新本地数据库... " + socketData.size() + "条");
            LocalSqlUtil.updateBookInfo(socketData);
            LOGGER.info("更新结束... ");
        }
    }

    //--------------------------- 返回结果方法群 start -----------------------------
    /**
     * 图书对象数组
     */
    public Map<String, BookInfo> getResBookMap() {
        return this.bookMap;
    }

    /**
     * 报表文件路径
     */
    public String getReportPath(){
        return this.reportPath;
    }

    /**
     * 异常图书个数
     * @return
     */
    public int getAbnormalBookNums(){
        return this.abnormalBookNums;
    }
    //--------------------------- 返回结果方法群  end  -----------------------------
}
